library(MASS)
library(foreign)
library(Matching)
library(ggplot2)
library(gridExtra)
library(MatchIt)
library(Zelig) 
library(cem)
library(ebal)

setwd("/Users/mihwa/Google drive/Matching_optional protocol")  
data<-read.dta("/Users/mihwa/Google drive/Matching_optional protocol/matchiccpr.dta")

attach(data)

# The following will run a caliper matching algorithm on the collapsed ICCRP data.
# data will run matching diagnostics.
matchiccpr_II <- matchit(iccprboth ~ iccpronly+ p_polity2+ trans+ lnwdi_gdpc+ wdi_gdpgr+ ciri_physint+ fh_cl +fh_pr+ ucdp_type3+LINVP+eeuro+ lame+ meast+ ssafr+ easia+ seasia+ sasia+ pacific+ caribbean, data=data, method="genetic", estimand="ATT", pop.size=200, int.seed=9)
matcheddata_II <-match.data(matchiccpr_II)
write.dta(matcheddata_II, file="matchediccpr_II.dta")

## balance checking

covar<-data[,c("iccpronly", "p_polity2", "trans","lnwdi_gdpc","wdi_gdpgr", "ciri_physint", "fh_cl", "fh_pr", "ucdp_type3",
               "LINVP","eeuro", "lame", "meast", "ssafr", "easia", "seasia", "sasia", "pacific", "caribbean")]

fmla <- as.formula(paste("iccprboth~",paste(names(covar),collapse="+")))

g.weights <- GenMatch(Tr=iccprboth, X=covar, BalanceMatrix=covar, estimand="ATT",  pop.size= 200,int.seed=9)
mout.gm <-  Match(INVP, iccprboth,covar,BiasAdjust=F,Weight.matrix=g.weights, estimand="ATT")

bout.gm <- MatchBalance(fmla,match.out = mout.gm,print.level=0,ks=FALSE)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=TRUE)
bal.gm2 <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=FALSE)

bal.gm=bal.gm[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal.gm2<-bal.gm2[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal=cbind(bal.gm2,bal.gm)
bal=round(bal,3)
bal=data.frame(bal)
#colnames(bal) <- c("var", "mean_Tr","mean_Co","sdiff_pooled","pval","mean_Tr2","mean_Co2","sdiff_pooled2","pval2")

write.csv(bal,"bal_iccpr_II.csv")

